const { to } = require('await-to-js')
const Http = require('../../db/model/HttpModel')
const request = require('request');
const { sendSmsByTpl } = require('../smsCode/smsCode')
const { formatDate } = require('../index')

const startHttpMonitor = (httpMonitorTimer, ms) => {
    httpMonitorTimer = setInterval(async () => {
        let [err, result] = await to(Http.find({ status: 1 }))
        if (err) return console.log(err)
        let length = result.length
        if (!length) return

        result.forEach(item => {
            request.get({
                url: item.url,
            }, (error, response, body) => {
                let urlStatus = 2
                body = body || ''
                if (body.includes(item.mark)) {
                    urlStatus = 1
                }
                let dateStr = formatDate()
                if (urlStatus !== item.urlStatus) {
                    //离线
                    if (urlStatus === 2) {
                        Http.updateOne({ _id: item._id }, { urlStatus, stopTime: dateStr }).then(() => { }).catch(() => { })
                        if (item.notifyStatus === 1) {
                            sendSmsByTpl(item.phone, {urlname: item.remarks, status: '离线', lasttime: item.lastTime} ,'TP1911205').then(() => {}).catch(err => { return console.log(err) })
                        }
                    //恢复上线
                    } else if (urlStatus === 1) {
                        Http.updateOne({ _id: item._id }, { urlStatus }).then(() => { }).catch(() => { })
                        if (item.notifyStatus === 1) {
                            sendSmsByTpl(item.phone, {urlname: item.remarks, status: '恢复上线', lasttime: item.lastTime} ,'TP1911205').then(() => {}).catch(err => { return console.log(err) })
                        }
                    }
                }
                Http.updateOne({ _id: item._id }, { lastTime: dateStr }).then(() => { }).catch(err => { return console.log(err) })
            })
        })
    }, ms)
}

module.exports = {
    startHttpMonitor
}